package com.k2data.etl;

import vcommon.utils.TimeUtils;
import vcommon.utils.httpclient.HttpMethod;
import vcommon.utils.httpclient.HttpsUtil;
import vcommon.utils.httpclient.SimpleHttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jodd.io.FileUtil;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class BqSime3 {
    private static Map<String, String> authHeader = new HashMap<>();
    private String outDir = "d:/work/";

    public static void main(String[] args) throws Exception {
        BqSime3 sime = new BqSime3();
        try {

            HttpClient httpClient = HttpsUtil.getHttpClient();

            // login
            request(httpClient, RequestConfUtil.getLoginRequest(), sime.outDir);

            // request for create query job
            RequestConf rc = RequestConfUtil.getR4();
            rc.getHeaders().putAll(authHeader);
            SimpleHttpResponse response = request(httpClient, rc, sime.outDir);

            // get status of job
            JSONObject jsonObject = JSON.parseObject(response.getText());

            // query status
            String statusUrl = jsonObject.getString("location");

            rc = RequestConfUtil.getRequest(statusUrl);
            rc.getHeaders().putAll(authHeader);

            response = request(httpClient, rc, sime.outDir);

            JSONObject jsonObject1 = JSON.parseObject(response.getText());
            int progress = jsonObject1.getInteger("progress");
            int lastProgress = progress;

            System.out.println(progress);

            while (progress != 100) {

                response = request(httpClient, rc, sime.outDir);

                jsonObject1 = JSON.parseObject(response.getText());
                progress = jsonObject1.getInteger("progress");

                if (progress > lastProgress) {
                    lastProgress = progress;
                    System.out.println(progress);
                }

                TimeUnit.SECONDS.sleep(1);
            }

            // query result
            String resultUrl = jsonObject1.getString("location");

            rc = RequestConfUtil.getRequest(resultUrl);
            rc.getHeaders().putAll(authHeader);

            response = request(httpClient, rc, sime.outDir);

            jsonObject1 = JSON.parseObject(response.getText());
            String nextResultUrl = jsonObject1.getString("next");
            while (nextResultUrl != null && nextResultUrl.length() > 0) {
                System.out.println("url : " + nextResultUrl);
                rc = RequestConfUtil.getRequest(nextResultUrl);
                rc.getHeaders().putAll(authHeader);

                response = request(httpClient, rc, sime.outDir);

                System.out.println("status code : " + response.getStatusCode());

                jsonObject1 = JSON.parseObject(response.getText());
                nextResultUrl = jsonObject1.getString("next");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static SimpleHttpResponse request(HttpClient httpClient, RequestConf rc, String outDir) {
        try {
            SimpleHttpResponse response = HttpsUtil.request(httpClient, rc.getUrl(), rc.getHeaders(), HttpMethod.valueOf(rc.getMethod()), (rc.getBody() == null || rc.getBody().size() == 0) ? rc.getBodyStr() : JSON.toJSONString(rc.getBody()), null);
            saveResponseToFile(response, outDir, rc);

            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static void saveResponseToFile(SimpleHttpResponse response, String outDir, RequestConf rc) throws IOException {
        StringBuilder sb = new StringBuilder();

        sb.append(rc.getUrl()).append("\n");

        sb.append(response.getStatusCode()).append("\n");
        sb.append(response.getReason()).append("\n");

        sb.append("\n").append("\n");

        for (Header header : response.getHeaders()) {
            sb.append(header.getName()).append("=").append(header.getValue()).append("\n");
            if ("Set-Cookie".equals(header.getName())) {
                authHeader.put("Cookie", header.getValue());
            }
            if ("Xsrf-Token".equals(header.getName())) {
                authHeader.put("X-Xsrf-Token", header.getValue());
            }
        }

        sb.append("\n").append("\n");

        sb.append(response.getText()).append("\n");

        FileUtil.writeString(new File(outDir + "/" + TimeUtils.now()), sb.toString());
    }

}
